package org.springagg.webapp.service.impl;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springagg.webapp.bean.Role;
import org.springagg.webapp.bean.User;
import org.springagg.webapp.dao.ResourceMapper;
import org.springagg.webapp.dao.RoleMapper;
import org.springagg.webapp.dao.UserMapper;
import org.springagg.webapp.service.UserService;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

	@Resource
	private UserMapper usermapper;

	@Resource
	private RoleMapper rolemapper;

	@Resource
	private ResourceMapper resourcemapper;

	@Override
	public int add(User user) {
		return usermapper.add(user);
	}

	@Override
	public int update(User user) {
		return usermapper.update(user);
	}

	@Override
	public int delete(int uid) {
		return usermapper.delete(uid);
	}

	@Override
	public User get(int uid) {
		return usermapper.get(uid);
	}

	@Override
	public User find(String username) {
		return usermapper.find(username);
	}

	@Override
	public List<User> all() {
		return usermapper.all();
	}

	@Override
	public Set<String> getRoles(String username) {
		User user = usermapper.find(username);
		List<Role> roles = rolemapper.all();
		if (user != null && roles != null) {
			Set<String> sets = new HashSet<String>();
			String ids = user.getRoles();
			for (Role role : roles) {
				if (ids.indexOf(String.valueOf(role.getRid())) > -1)
					sets.add(role.getRole());
			}
			return sets;
		}
		return Collections.emptySet();
	}

	@Override
	public Set<String> getPermissions(String username) {
		User user = usermapper.find(username);
		List<Role> roles = rolemapper.all();
		if (user != null && roles != null) {
			Set<String> reids = new HashSet<String>();
			String ids = user.getRoles();
			for (Role role : roles) {
				if (ids.indexOf(String.valueOf(role.getRid())) > -1)
					reids.add(role.getResources());
			}
			return getPermisions(reids);
		}
		return Collections.emptySet();
	}

	private Set<String> getPermisions(Set<String> reids) {
		List<org.springagg.webapp.bean.Resource> resources = resourcemapper.all();
		Set<String> perms = new HashSet<String>();
		String ids = Arrays.toString(reids.toArray(new String[reids.size()]));
		if (resources != null && resources.size() > 0 && reids.size() > 0) {
			for (org.springagg.webapp.bean.Resource resource : resources) {
				if (ids.indexOf(String.valueOf(resource.getReid())) > -1)
					perms.add(resource.getPermission());
			}
			return perms;
		}
		return null;
	}
}
